package at.cookieforensics;
import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * This class represents a response from a webserver, it has functionality to
 * decide whether the user is logged in or not
 * 
 * @author Martin Grottenthaler
 *
 */
public class CookieSite {
	/**
	 * source code of a website
	 */
	private String sourceCode = null;
	/**
	 * corresponding domain name
	 */
	private String domain = null;
	/**
	 * whether user is logged in or not
	 */
	private boolean loggedIn = false;
	/**
	 * message with result of login check
	 */
	private String message = "";
	
	/**
	 * sets sourceCode and domain
	 * @param sourceCode source of website
	 * @param domain corresponding domain
	 */
	public CookieSite(String sourceCode, String domain) {
		this.sourceCode = sourceCode;
		this.domain = domain;
		
		message = loginCheck();
	}
	
	/**
	 * checks whether logged in or not
	 * first check is if service is in supported service list
	 * then check if source code is indicating that user is not logged in
	 * @return string which describes outcome of check
	 */
	private String loginCheck() {
		/*
		if (!UI.getServices().contains(domain)) {
			loggedIn = false;
			return "website not supported";
		
		}
		*/
		String loggedOutCode = null;
		
		Document doc = null;
		try {
			File xmlFile = new File("loginCodes.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(xmlFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		doc.getDocumentElement().normalize();
		
		NodeList nList = doc.getElementsByTagName("service");
		
		for (int i = 0; i < nList.getLength(); i++) {
			Node nNode = nList.item(i);
			
			if (nNode.getNodeType() == Node.ELEMENT_NODE) {
				 
				Element eElement = (Element) nNode;
	 
				if (domain.equals(eElement.getAttribute("domain"))) {
					loggedOutCode = eElement.getElementsByTagName("loggedOut").item(0).getTextContent();
				}
			}
		}

		if (sourceCode.contains(loggedOutCode)) {
			loggedIn = false;
		} else {
			loggedIn = true;
		}
		
		if (loggedIn) {
			return "Cookie OK";
		} else {
			return "Not logged in or service not supported";
		}
	}

	/**
	 * returns whether user is logged in or not
	 * @return login status
	 */
	public boolean isLoggedIn() {
		return loggedIn;
	}

	/**
	 * return status message from login check
	 * @return status message
	 */
	public String getMessage() {
		return message;
	}
}